#!/usr/bin/env python
# -*- encoding: utf8 -*-

from __future__ import with_statement
import os
import sys
import settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
sys.path.append('../')
from reps.interns.models import *

if len(sys.argv)<3:
    print 'To run program write:\n\t'+sys.argv[0]+' command file_name\ncommands:\n\timport - import companies to database'

if sys.argv[1]=='import':
    with open(sys.argv[2]) as file:
        user = User.objects.filter(is_staff=True)[0]
        lines = 0
        for line in file.read().split('\n'):
            company = line.split(';')
            if len(company)>=5:
                lines += 1
                tmp_company = Branch()
                tmp_company.name = company[0].decode('utf-8')
                tmp_company.street = company[1].decode('utf-8')
                tmp_company.postal_code = company[2].decode('utf-8')
                tmp_company.city = company[3].decode('utf-8')
                tmp_company.country = company[4].decode('utf-8')
                tmp_company.created_by = user
                tmp_company.main_branch = None
                tmp_company.save()
    print 'Added ' + str(lines) + ' companies.'
elif sys.argv[1]=='export':
    with open(sys.argv[2], 'w') as file:
        branches = Branch.objects.all()
        for branch in branches:
            line = branch.name+';'+branch.street+';'+branch.postal_code+';'+branch.city+';'+branch.country
            file.write(line)
else:
    print 'Wrong option'